<?php

namespace common\models\product;

use Yii;
use \common\models\goods\Goods;
use \common\models\product\ProductLockItem;

/**
 * 这个模型基于表 "{{%product}}" 生成。
 *
 * @property integer $id
 * @property integer $goods_id
 * @property string $sn
 * @property string $sn_purchase
 * @property string $sn_intel
 * @property string $goods_attr
 * @property string $goods_attr_str
 * @property integer $number_stock
 * @property integer $number_lock
 * @property string $price_market
 * @property string $price_cost
 * @property string $img
 * @property string $name_short
 * @property integer $is_buy_min_disable
 * @property integer $is_buy_setp_disable
 * @property integer $weight
 */
class Product extends \common\models\AR {

    public $modelName = '货品';

    const LOCK_TYPE_ORDER = 1;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%product}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['goods_id', 'sn', 'supplier_id'], 'required'],
            [['goods_id', 'number_stock', 'number_lock', 'is_buy_min_disable', 'is_buy_setp_disable', 'weight'], 'integer'],
            [['price_market', 'price_cost'], 'number'],
            [['sn', 'sn_purchase', 'sn_intel'], 'string', 'max' => 20],
            [['goods_attr'], 'string', 'max' => 15],
            [['goods_attr_str'], 'string', 'max' => 150],
            [['img'], 'string', 'max' => 45],
            [['name_short', 'slot'], 'string', 'max' => 50],
            [['number_stock', 'number_lock'], 'default', 'value' => 0],
                //[['sn'], 'unique'],
                //[['sn_intel'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'goods_id' => '商品',
            'sn' => '货品编号',
            'sn_purchase' => '厂家编码',
            'sn_intel' => '国际码',
            'goods_attr' => '货品属性ID',
            'goods_attr_str' => '货品属性',
            'number_stock' => '实际库存',
            'number_lock' => '锁定数量',
            'price_market' => '市场价',
            'price_cost' => '进货价',
            'img' => '货品图片路径',
            'name_short' => '短名称',
            'is_buy_min_disable' => '最小起订量是否失效   0否 1是  主要用于当库存数量',
            'is_buy_setp_disable' => '递增数量是否失效  如果失效，则默认递增数量为1   0否 1是',
            'weight' => '重量（克）',
            'slot' => '货位',
        ];
    }

    public function afterDelete() {
        parent::afterDelete();
        $condition = 'product_id=:product_id';
        $params = [':product_id' => $this->id];
        ProductBuyMin::deleteAll($condition, $params);
        ProductPrices::deleteAll($condition, $params);
        ProductLockItem::deleteAll($condition, $params);
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
    }

    public function getGoods() {
        return $this->hasOne(Goods::className(), ['id' => 'goods_id']);
    }

    public function getMins() {
        $ret = [
            Goods::SELL_TYPE_RETAIL => new ProductBuyMin,
            Goods::SELL_TYPE_MIX => new ProductBuyMin,
            Goods::SELL_TYPE_PACK => new ProductBuyMin,
        ];


        if (intval($this->id) > 0) {
            $all = ProductBuyMin::findAll(['product_id' => $this->id]);
            if ($all) {
                foreach ($all as $item) {
                    $ret[$item->type] = $item;
                }
            }
        }

        return $ret;
    }

    public function getPrices() {
        $ret = [
            Goods::SELL_TYPE_RETAIL => [],
            Goods::SELL_TYPE_MIX => [],
            Goods::SELL_TYPE_PACK => [],
        ];

        if (intval($this->id) > 0) {
            $all = ProductPrices::find()->where(['product_id' => $this->id])->orderBy(['type' => SORT_ASC, 'number' => SORT_ASC])->all();

            //类型分类
            foreach ($all as $item) {
                $ret[$item->type][] = $item;
            }
        }

        //价格梯度数量不够，补足
        foreach ($ret as $type => $item) {
            for ($i = count($item); $i < 3; $i++) {
                $ret[$type][] = new ProductPrices;
            }
        }

        return $ret;
    }

    /**
     * 增加或减少货品数量
     * @param ProductStockLog $log 
     */
    public function updateStock(ProductStockLog $log) {
        $this->number_stock += $log->number;
        $this->save() && $log->save();
        $this->goods->updateStock();
    }

    /**
     * 锁定货品数量
     * @param intval $num 锁定数量
     * @param intval $itemType 被锁定的项目类型
     * @param intval $itemId 项目ID
     * @return boolean
     */
    public function lockStock($num, $itemType, $itemId) {
        if ($this->isNewRecord) {
            return FALSE;
        }

        $this->number_lock += $num;
        if ($this->save()) {
            $productLockItem = ProductLockItem::findOne(['product_id' => $this->id, 'type' => $itemType, 'item_id' => $itemId]);
            !$productLockItem && $productLockItem = new ProductLockItem;
            $productLockItem->setAttributes([
                'product_id' => $this->id,
                'number' => $num,
                'type' => $itemType,
                'item_id' => $itemId,
            ]);
            $productLockItem->save();
        }
    }

    /**
     * 将锁定的货品数量解锁
     * @param intval $num 解锁数量
     * @param intval $itemType 解锁的项目类型
     * @param intval $itemId 项目ID
     * @param boolean $isUpdateStock 是否扣除实际的库存数量，默认为TRUE
     * @return boolean
     */
    public function unlockStock($num, $itemType, $itemId, $isUpdateStock = true) {
        if ($this->isNewRecord) {
            return FALSE;
        }
        $this->number_lock-= $num;
        $isUpdateStock && $this->number_stock-= $num;
        if ($this->save()) {
            $productLockItem = ProductLockItem::findOne(['product_id' => $this->id, 'type' => $itemType, 'item_id' => $itemId]);
            $productLockItem && $productLockItem->delete();
        }
    }

}
